<template>
  <div class="app-container">
    <el-card class="tableset" shadow="never" :body-style="{ padding: '0px' }">
      <!-- 小标题 -->
      <div>
        <span class="title">广告管理</span>
      </div>
      <!-- 小标题 -->

      <!-- 搜索关键词 -->
      <div class="funtion">
        <el-input
          v-model="get_advertising_info_list.keyword"
          placeholder="请输入关键词"
          class="input-with-select"
          clearable
          @keyup.enter.native="getAdminUserInfoList"
        >
          <el-select
            slot="prepend"
            v-model="get_advertising_info_list.keywordType"
            placeholder="请选择"
            class="option"
          >
            <el-option label="广告位名称" :value="0" />
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="getAdminUserInfoList" />
        </el-input>
      </div>
      <!-- 搜索关键词 -->

      <!-- 数据表 -->
      <el-table
        v-loading="dataRequestLoading"
        element-loading-text="正在加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        :data="data_advertising_info_list.data"
        class="table"
        :height="tableHeight"
        :max-height="tableHeight"
        highlight-current-row
        style="width: 100%;"
        @sort-change="changeSort"
      >
        <el-table-column prop="name" label="广告位名称" />
        <el-table-column prop="create_time" label="创建时间" sortable="custom" />
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              @click="openUpDateAdverisingInfoDialog(row)"
            >编 辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据表 -->

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        layout="total, sizes,prev, pager, next, jumper"
        :total="data_advertising_info_list.total"
        :page-size="get_advertising_info_list.pageSize"
        :page-sizes="[20, 50, 100]"
        :current-page="get_advertising_info_list.currentPage"
        @size-change="changePageSize"
        @current-change="changeCurrentPage"
      />
      <!-- 分页 -->
    </el-card>

    <!-- 修改广告信息dialog -->
    <el-dialog
      title="修改广告信息"
      :visible.sync="upDateAdverisingInfoDialog"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="upDateAdverisingInfoRulesForm"
        :model="upData_adverising_info"
        status-icon
        size="mini"
        label-width="90px"
      >
        <el-form-item prop="name" :rules="rules.input" label="广告位名称">
          <el-input v-model="upData_adverising_info.name" placeholder="请输入广告位名称" clearable />
        </el-form-item>
        <el-form-item v-for="(item, index) in upData_adverising_info.path" :key="index" :label="`跳转路由${index+1}`">
          <el-input v-model="item.url" style="width: 300px;" placeholder="请输入跳转路由" clearable />
          <span>广告位类型</span>
          <el-radio-group v-model="item.advertising_type">
            <el-radio-button :label="0">广告文章</el-radio-button>
            <el-radio-button :label="1">路由地址</el-radio-button>
            <el-radio-button :label="2">非广告</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="path" :rules="rules.image" label="上传广告图（不超过8张）">
          <el-upload
            action
            :auto-upload="false"
            list-type="picture-card"
            :file-list="upData_adverising_info.show_path"
            :show-file-list="true"
            :limit="8"
            :on-change="changeUploadImage"
            :on-exceed="checkNumber"
            :on-preview="handlePictureCardPreviewImage"
            :on-remove="handleRemoveImage"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="upDateAdverisingInfoDialog = false">取 消</el-button>
        <el-button type="primary" @click="upDateAdvertisingInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改广告信息dialog -->

    <!-- 查看图片dialog -->
    <el-dialog :visible.sync="imageDialog" custom-class="full-dialog">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>
    <!-- 查看图片dialog -->

    <!-- 剪切图片dialog -->
    <el-dialog title="图片剪裁" :visible.sync="UploadImagerDialog" :close-on-click-modal="false">
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :info="option.info"
            :output-size="option.size"
            :output-type="option.outputType"
            :can-scale="option.canScale"
            :auto-crop="option.autoCrop"
            :auto-crop-width="option.autoCropWidth"
            :auto-crop-height="option.autoCropHeight"
            :cropper-width="option.cropperWidth"
            :cropper-height="option.cropperHeight"
            :fixed-box="option.fixedBox"
            :fixed="option.fixed"
            :fixed-number="option.fixedNumber"
            :full="option.full"
            :can-move-box="option.canMoveBox"
            :original="option.original"
            :center-box="option.centerBox"
            :info-true="option.infoTrue"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="UploadImagerDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="uploadLoading" @click="upLoadImage">确认</el-button>
      </div>
    </el-dialog>
    <!-- 剪切图片dialog -->
  </div>
</template>

<script>
import { getFormData } from '@/common/js/until'
import { uploadImage } from '@/api/upload'
import { getAdminUserInfoList, upDateAdvertisingInfo } from '@/api/advertssing-manage'

export default {
  data() {
    return {
      // table高度自适应
      tableHeight: window.innerHeight - 265,

      // loading开关
      dataRequestLoading: false,
      uploadLoading: false,

      // dialog 开关
      upDateAdverisingInfoDialog: false,
      UploadImagerDialog: false,

      // 展示图片
      imageDialog: false,
      dialogImageUrl: false,

      // 图片裁剪框
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 600, // 默认生成截图框宽度
        autoCropHeight: 300, // 默认生成截图框高度
        cropperWidth: 600, // 截图框宽度
        cropperHeight: 300, // 截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: false, // 是否开启截图框宽高固定比例
        fixedNumber: [2, 1], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: false, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: true, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },

      // 发起查询请求参数
      get_advertising_info_list: {
        pageSize: 20,
        currentPage: 1,
        keyword: '',
        keywordType: 0,
        sort_name: '',
        sort: 'desc'
      },

      // 查询返回值
      data_advertising_info_list: {
        data: [],
        total: 0
      },

      // 修改广告位信息参数
      upData_adverising_info: {
        advertising_id: '',
        name: '',
        path: [],
        show_path: []
      },

      // 表单校验规则
      rules: {
        input: { required: true, message: '请输入广告位名称！', trigger: 'blur' },
        image: { required: true, message: '请上传广告图！', trigger: 'blur' }
      }
    }
  },
  mounted() {
    this.getAdminUserInfoList() // 查询广告信息列表
  },
  methods: {
    // 查询广告信息列表
    getAdminUserInfoList() {
      this.dataRequestLoading = true
      getAdminUserInfoList(this.get_advertising_info_list).then(res => {
        res.result.showing.forEach(val => {
          val.path = JSON.parse(val.path)
        })
        this.data_advertising_info_list = {
          data: res.result.showing,
          total: res.result.total
        }
        this.dataRequestLoading = false
      })
    },

    // 打开编辑广告信息dialog
    openUpDateAdverisingInfoDialog(row) {
      this.upData_adverising_info = {
        advertising_id: row.advertising_id,
        name: row.name,
        path: [],
        show_path: []
      }
      if (row.path.length > 0) {
        row.path.forEach(val => {
          const path = {
            path: JSON.parse(val)['path'],
            url: JSON.parse(val)['url'],
            advertising_type: JSON.parse(val)['advertising_type']
          }
          const image = {
            url: process.env.VUE_APP_BASE_API + JSON.parse(val)['path'],
            path: JSON.parse(val)['path']
          }
          this.upData_adverising_info.path.push(path)
          this.upData_adverising_info.show_path.push(image)
        })
      }
      this.upDateAdverisingInfoDialog = true
    },

    // 修改广告信息
    upDateAdvertisingInfo() {
      this.$refs.upDateAdverisingInfoRulesForm.validate(valid => {
        if (valid) {
          upDateAdvertisingInfo(this.upData_adverising_info).then(res => {
            this.getAdminUserInfoList()
            this.upDateAdverisingInfoDialog = false
          })
        } else {
          return false
        }
      })
    },

    // 切换每页条数方法
    changePageSize(data) {
      this.get_advertising_info_list.pageSize = data
      this.getAdminUserInfoList()
    },

    // 切换页码方法
    changeCurrentPage(data) {
      this.get_advertising_info_list.currentPage = data
      this.getAdminUserInfoList()
    },

    // 更换排序
    changeSort({ column, order }) {
      switch (order) {
        case 'descending':
          this.get_advertising_info_list.sort_name = 'create_time'
          this.get_advertising_info_list.sort = 'desc'
          this.getAdminUserInfoList()
          break
        case 'ascending':
          this.get_advertising_info_list.sort_name = 'create_time'
          this.get_advertising_info_list.sort = 'asc'
          this.getAdminUserInfoList()
          break
        default:
          this.get_advertising_info_list.sort_name = ''
          this.get_advertising_info_list.sort = 'desc'
          this.getAdminUserInfoList()
      }
    },

    // 打开剪切界面
    changeUploadImage(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 2
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        fileList.pop()
        return false
      }
      if (file.raw.type !== 'image/jpeg' && file.raw.type !== 'image/png') {
        this.$message.error('上传图片只支持jpeg和png!')
        fileList.pop()
        return false
      }
      // 将图片地址赋值给裁剪框显示图片
      this.$nextTick(() => {
        fileList.pop()
        this.option.img = URL.createObjectURL(file.raw)
        this.UploadImagerDialog = true
      })
    },
    // 上传剪切后的图片
    upLoadImage() {
      this.$refs.cropper.getCropBlob(data => {
        const formData = getFormData(data, 'advertising-manage')
        uploadImage(formData).then(res => {
          const image = {
            url: process.env.VUE_APP_BASE_API + res.result,
            path: res.result
          }
          this.upData_adverising_info.show_path.push(image)
          const path = {
            path: res.result,
            url: '',
            advertising_type: 0
          }
          this.upData_adverising_info.path.push(path)
          this.UploadImagerDialog = false
        })
      })
    },
    // 检测上传数量
    checkNumber() {
      this.$message({ type: 'warning', message: '只能上传八张图片！' })
    },
    // 查看放大图
    handlePictureCardPreviewImage(file) {
      this.dialogImageUrl = file.url
      this.imageDialog = true
    },
    // 删除对应图片
    handleRemoveImage(file, fileList) {
      const indexShowPath = this.upData_adverising_info.show_path.indexOf(file)
      this.upData_adverising_info.show_path.splice(indexShowPath, 1)
      this.upData_adverising_info.path.splice(indexShowPath, 1)
    }
  }
}
</script>
